#!/bin/sh

# Copyright © 2009, 2010, 2011 Jakub Wilk
#
# This package is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 dated June, 1991.

set -e
set -x

pwd="$PWD"
buildroot=$(mktemp -dt pdf2djvu-source-XXXXXXXX)
export TAR_OPTIONS='--owner root --group root --mode a+rX'
export GZIP='-9n'

cd "$buildroot"

# Mercurial archive:
hg archive "$@" -R "$pwd" pdf2djvu
rm -f pdf2djvu/.hg*
version=$(sed -e '/.*(\([0-9.]\+\)).*/ { s//\1/g; q; }' < pdf2djvu/doc/changelog)
mv pdf2djvu "pdf2djvu-$version"

# Autoconf & company:
cd "pdf2djvu-$version"
for file in install-sh config.sub config.guess
do
  cp $(ls -d /usr/share/automake* | head -n1)/$file tools/
done
cp /usr/share/gettext/config.rpath tools/
mkdir m4/
aclocal -I m4 --install
autoconf
autoheader
rm -Rf *.cache
cd ..

# Build the manual page:
sed -n -e '/^AC_INIT(\(.*\), *\(.*\), *\(.*\), .*, .*)$/ { s//PACKAGE_NAME=\1\nPACKAGE_VERSION=\2\nPACKAGE_BUGREPORT=\3/p; q }' "pdf2djvu-$version/configure.ac" > "pdf2djvu-$version/Makefile.common"
make -C "pdf2djvu-$version/doc/"
make -C "pdf2djvu-$version/doc/po/"
rm "pdf2djvu-$version/Makefile.common"

# Build translations:
cd "pdf2djvu-$version/po/"
for file in *.po
do
  language="${file%.po}"
  msgfmt "$language.po" -o "$language.mo"
done
cd ../..

# Prepare tests:
make -C "pdf2djvu-$version/tests/" prepare

# Tarball with raw source:
tar -czf "$pwd/pdf2djvu_$version.tar.gz" "pdf2djvu-$version"

# Cleanup:
rm -Rf "$buildroot"
